/*
 * 
 *
 * Project  : VPC
 * Name   : MailUtil.java
 *
 * 
 */
package com.virtium.vpc.utils;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;



/**
 * Provides Mail utility methods that can be used to perform common operations.
 * This class using javax mail properties in handling its task.
 *
 * @author 
 * @version 
 * @since 
 */

public class MailUtil  {
	Thread updateThread = null;


    static Logger log = Logger.getLogger(MailUtil.class);
    private static final String INBOX = "INBOX", POP_MAIL = "pop3", SMTP_MAIL = "smtp";

    // See constants.properites to change the configuration
    private static final String SMTP_HOST = ApplicationConstant.get("smtp.host");
    private static final String SMTP_USER = ApplicationConstant.get("smtp.user");
    private static final String SMTP_PASSWORD = ApplicationConstant.get("smtp.password");
    private static final String SMTP_AUTH = ApplicationConstant.get("smtp.auth");
    private static final String DEFAULT_SENDER_NAME = ApplicationConstant.get("default.sender.name");

    

        
    public static class sendEmailThread extends Thread 
    {
        private static final String INBOX = "INBOX", POP_MAIL = "pop3", SMTP_MAIL = "smtp";

        // See constants.properites to change the configuration
        private static final String SMTP_HOST = ApplicationConstant.get("smtp.host");
        private static final String SMTP_USER = ApplicationConstant.get("smtp.user");
        private static final String SMTP_PASSWORD = ApplicationConstant.get("smtp.password");
        private static final String SMTP_AUTH = ApplicationConstant.get("smtp.auth");
        private static final String DEFAULT_SENDER_NAME = ApplicationConstant.get("default.sender.name");
        
        String from= null ;
    	String to= null ;
    	String cc= null ;
    	String bcc= null ;
    	String Subject= null ;
    	String bodyText = null;
    	String filename = null;
        public sendEmailThread(String from, String to, String cc, String bcc, String Subject, String bodyText, String filename)
        {
        	this.from = from ;
        	this.to = to;
        	this.cc =cc; 
        	this.bcc =bcc;
        	this.Subject =Subject;
        	this.bodyText = bodyText;
        	this.filename = filename;
        }
    	public void run() 
    	{
    		if(filename == null || "".equals(filename))
    		{
    			sendEmail(from, to, cc, bcc, Subject, bodyText);
    		}
    		else
    		{
    			sendEmailWithAttachment(from, to, cc, bcc, Subject, bodyText, filename);    			
    		}
    	}
        public static boolean sendEmail(String from, String to, String cc, String bcc, String Subject, String bodyText) {
            try {
                Properties props = System.getProperties();
                props.setProperty("mail.transport.protocol", SMTP_MAIL);
                props.setProperty("mail.host", SMTP_HOST);
                props.setProperty("mail.user", SMTP_USER);
                props.setProperty("mail.password", SMTP_PASSWORD);
                props.setProperty("mail.smtp.auth", SMTP_AUTH);
                Session mailSession = Session.getDefaultInstance(props, null);
                Message msg = new MimeMessage(mailSession);
                InternetAddress[] _toList = null, _ccList = null, _bccList = null;

                if (to != null) {
                    _toList = InternetAddress.parse(to);
                    msg.setRecipients(javax.mail.Message.RecipientType.TO, _toList);
                }
                if (cc != null) {
                    _ccList = InternetAddress.parse(cc);
                    msg.setRecipients(javax.mail.Message.RecipientType.CC, _ccList);
                }
                if (bcc != null) {
                    _bccList = InternetAddress.parse(bcc);
                    msg.setRecipients(javax.mail.Message.RecipientType.BCC, _bccList);
                }

                msg.setFrom(new InternetAddress(from, DEFAULT_SENDER_NAME));
                msg.setSubject(Subject);
                msg.setContent(bodyText, "text/html");

                if (log.isDebugEnabled()) {
                    log.debug("From: " + from);
                    log.debug("To: " + to);
                    log.debug("Cc: " + cc);
                    log.debug("Bcc: " + bcc);
                    log.debug("Subject: " + Subject);
                }

                // Send message
                
                //tuandang, 13/9
                //end of tuandang, 13/9
                
                
                
                
                Transport transport = mailSession.getTransport(SMTP_MAIL);
                transport.connect(SMTP_HOST, SMTP_USER, SMTP_PASSWORD);
                msg.saveChanges();
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();

            } catch (AddressException ae) {
                //thrown when a wrongly formatted address is encountered.
                log.error(ae);
                return false;
            } catch (SendFailedException sfe) {
                //thrown when the message cannot be sent.
                log.error(sfe);
                return false;
            } catch (MessagingException me) {
                //The base class for all exceptions thrown by the Messaging classes
                log.error(me);
                return false;
            } catch (Exception e) {
                log.error(e);
                return false;
            }

            return true;
        }
        /**
         * Send email with attachment to severals recipients.
         *
         * @param from
         * @param to
         * @param cc
         * @param bcc
         * @param Subject
         * @param body
         * @param filename
         */
        public static boolean sendEmailWithAttachment(String from, String to, String cc, String bcc, String Subject, String body, String filename) {
            try {
                Properties props = System.getProperties();
                props.setProperty("mail.transport.protocol", SMTP_MAIL);
                props.setProperty("mail.host", SMTP_HOST);
                props.setProperty("mail.user", SMTP_USER);
                props.setProperty("mail.password", SMTP_PASSWORD);
                props.setProperty("mail.smtp.auth", SMTP_AUTH);
                Session mailSession = Session.getDefaultInstance(props, null);
                Message msg = new MimeMessage(mailSession);
                InternetAddress[] _toList = null, _ccList = null, _bccList = null;

                if (to != null) {
                    _toList = InternetAddress.parse(to);
                    msg.setRecipients(javax.mail.Message.RecipientType.TO, _toList);
                }
                if (cc != null) {
                    _ccList = InternetAddress.parse(cc);
                    msg.setRecipients(javax.mail.Message.RecipientType.CC, _ccList);
                }
                if (bcc != null) {
                    _bccList = InternetAddress.parse(bcc);
                    msg.setRecipients(javax.mail.Message.RecipientType.BCC, _bccList);
                }

                msg.setFrom(new InternetAddress(from, DEFAULT_SENDER_NAME));
                msg.setSubject(Subject);

                // Attach file with message
                File file = new File(filename);
//                if (file.exists()) {
                    // create and fill the first message part
                    MimeBodyPart mbp1 = new MimeBodyPart();
                    //mbp1.setText(body);
                    mbp1.setContent(body, "text/html");

                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(filename);
                    mbp2.setDataHandler(new DataHandler(fds));
                    String fileName2 = fds.getName();
                    fileName2 = fileName2.substring(fileName2.indexOf("_")+1, fileName2.length());
                    mbp2.setFileName(fileName2);

                    // create the Multipart and its parts to it
                    Multipart mp = new MimeMultipart();
                    mp.addBodyPart(mbp1);
                    mp.addBodyPart(mbp2);

                    // add the Multipart to the message
                    msg.setContent(mp);
                    
//                } else {
//                    msg.setText(body);
//                }
                
                if (log.isDebugEnabled()) {
                    log.debug("From: " + from);
                    log.debug("To: " + to);
                    log.debug("Cc: " + cc);
                    log.debug("Bcc: " + bcc);
                    log.debug("Subject: " + Subject);
                    log.debug("Attachment: " + filename);
                }

                // Send message
                Transport transport = mailSession.getTransport(SMTP_MAIL);
                transport.connect(SMTP_HOST, SMTP_USER, SMTP_PASSWORD);
                msg.saveChanges();
                transport.sendMessage(msg, msg.getAllRecipients());
                transport.close();
                FileUtil.deleteFile(filename);
            } catch (AddressException ae) {
                //thrown when a wrongly formatted address is encountered.
                log.error(ae);
                return false;
            } catch (SendFailedException sfe) {
                //thrown when the message cannot be sent.
                log.error(sfe);
                return false;
            } catch (MessagingException me) {
                //The base class for all exceptions thrown by the Messaging classes
                log.error(me);
                return false;
            } catch (Exception e) {
                log.error(e);
                return false;
            }

            return true;
        }
    }

    //end of tuandang, 13/9
	/**
     * Send email to severals recipients.
     *
     * @param from
     * @param to
     * @param cc
     * @param bcc
     * @param Subject
     * @param bodyText
     */
    public static boolean sendEmail(String from, String to, String cc, String bcc, String Subject, String bodyText) 
    {
    	try {
        	new sendEmailThread(from, to, cc, bcc, Subject, bodyText, "").start();			
		} catch (Exception e) {
	    	return false;
		}
    	return true;
    }

    
    /**
     * Send email to one specific recipient.
     *
     * @param from
     * @param to
     * @param Subject
     * @param message
     */
    public static boolean sendEmail(String from, String to, String Subject, String message) {
        return sendEmail(from, to, null, null, Subject, message);
    }

    /**
     * Send email to one specific recipient and bcc.
     *
     * @param from
     * @param to
     * @param bcc
     * @param Subject
     * @param message
     */
    public static boolean sendEmail(String from, String to, String bcc, String Subject, String message) {
        return sendEmail(from, to, null, bcc, Subject, message);
    }

    /**
     * Send email with attachment to one specific recipient and bcc.
     *
     * @param from
     * @param to
     * @param bcc
     * @param Subject
     * @param message
     */
    public static boolean sendEmailWithAttachment(String from, String to, String bcc, String Subject, String message, String filename) {
    	try {
        	new sendEmailThread(from, to, null, bcc, Subject, message, filename).start();			
		} catch (Exception e) {
	    	return false;
		}
    	return true;
    }
    
    /**
     * Send email with attachment to one specific recipient and bcc.
     *
     * @param from
     * @param to
     * @param bcc
     * @param Subject
     * @param message
     */
    public static boolean sendEmailWithAttachment(String from, String to, String Subject, String message, String filename) 
    {
    	try {
        	new sendEmailThread(from, to, null, null, Subject, message, filename).start();			
		} catch (Exception e) {
	    	return false;
		}
    	return true;
    }
}
